package com.lge.clock;

import java.io.FileOutputStream;

import java.io.IOException;
import java.io.InputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;

import com.lge.clock.util.CommonUtil;
import com.lge.clock.worldclock.DeleteListActivity;
import com.lge.clock.worldclock.ListSearchActivity;
import com.lge.clock.worldclock.LowOnSpaceDialog;
import com.lge.clock.worldclock.MapSearchActivity;
import com.lge.clock.worldclock.WorldClockAdapter;
import com.lge.clock.worldclock.accuweather.WeatherUtil;
import com.lge.clock.worldclock.cities.CityDBManager;
import com.lge.clock.worldclock.cities.CityInformation;
import com.lge.clock.worldclock.util.DatabaseHelper;
import com.lge.clock.worldclock.util.WCPreferences;

import android.app.AlertDialog;

import android.app.Fragment;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnDismissListener;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.format.Time;
import android.util.Log;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.View.OnClickListener;
import android.view.View.OnCreateContextMenuListener;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.Toast;
import android.widget.AdapterView;

import com.lge.sui.widget.dialog.SUIProgressDialog;

/**
 * @author lge.com
 */
public class WorldClockFragment extends Fragment implements OnClickListener, OnCreateContextMenuListener {
	private static final String TAG = "WorldClockFragment"; 
	private ListView cityListView;
	private View noCityView;
	
//	public static boolean clockVisible;
	
	private static final int DELETE_DIALOG = 1;
	private static final int DELETEALL_DIALOG = 2;
	private static final int DST_SELECT_DIALOG = 3;

	
	private static final int SEARCHLIST_ACTIVITY = 1;
	private static final int SEARCHMAP_ACTIVITY = 2;
	private static final int MULTIDELETE_ACTIVITY = 4;
	
	private static final int CONTEXT_DELETE = Menu.FIRST + 1;
	private static final int CONTEXT_DST = Menu.FIRST + 2;
	
	private static final int MAXIMUM_WORLDCLOCK_LIST_SIZE = 20;
	
	private static CityInformation selectedItem;
	private static WorldClockAdapter mWCAdapter;
	
	private static int selectIndexDST = 0;
	private static int notDSTUpdateCount = 0;
	
	private CityDBManager mCityManager;
	private TheBroadcastReceiver intentReceiver = null;
	private ArrayList<CityInformation> cityInfoArray = null;
	
	private boolean receiverNetworkFlag = false;
	private boolean isLowOnSpace = false; //[hyunjung78.park][1406] 2011.10.12 
	
    private Menu menu;
	
    private boolean mSelectedOptionItem = false;
    /** Called when the activity is first created. */
    @Override 
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setHasOptionsMenu(true);
        mSelectedOptionItem = false;
		isLowOnSpace = CommonUtil.isLowOnSpaceMemory(this.getActivity());
		if(isLowOnSpace) {		

			Intent mIntent = new Intent(this.getActivity(), LowOnSpaceDialog.class);
			mIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_NO_USER_ACTION);
			this.startActivity(mIntent);

			this.getActivity().finish();
			return;
		}
		
//    	boolean isDBupdated = false;
		cityInfoArray = new ArrayList<CityInformation>();
		WCPreferences wcPref = new WCPreferences(getActivity());
		if((!CityDBManager.isExistDatabase(getActivity()))
				|| (DatabaseHelper.getDataBaseVer() > wcPref.getDatabaseVersion())) {	
			Log.i(TAG, "Update worldClock database");			
			new UpdateDataBase().execute(0);
//			isDBupdated = true;
		}
		else {
			/*[START] 2011.12.30 suein1209.kim INTERNAL_TEST.SDQ_11 - Defect #111661 */
			initCityDBManager();
			/*[END] 2011.12.30 suein1209.kim INTERNAL_TEST.SDQ_11 - Defect #111661 */
			cityInfoArray.addAll(mCityManager.getWorldClockList(getActivity().getApplicationContext()));
		}
         
//		cityInfoArray = new ArrayList<CityInformation>();
//		if(!isDBupdated) {
//			cityInfoArray.addAll(mCityManager.getWorldClockList(getActivity().getApplicationContext()));
//		}
    }
    
    /**
     * 2011.12.30 suein1209.kim INTERNAL_TEST.SDQ_11 - Defect #111661
     * init city DB Manager
     */
    private void initCityDBManager(){
    	
    	if(mCityManager == null){
    		try {
    			mCityManager = CityDBManager.getInstance(getActivity());
    		} catch (IOException e) {
    			Log.e(TAG, e.getMessage());
    		}
    	}else{
    		/*Do nothing*/
    	}//End Of if
    	
    } //End Of Method initCityDBManager
    
    @Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {

    	
        return initView(inflater, container);
	}


	public boolean checkDBVer(){
    	boolean result = false;
    	WCPreferences WcPref = new WCPreferences(getActivity());
    	if(DatabaseHelper.getDataBaseVer() > WcPref.getDatabaseVersion()){
    		result = true;
    	}
    	return result;
    }
	@Override
	public void onStop() {
		Log.i(TAG, "onStop");
		// TODO Auto-generated method stub		
		super.onStop();
	}
	
    @Override
	public void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
    	if(intentReceiver!=null){
        	try{
    			getActivity().unregisterReceiver(intentReceiver);
    			}catch(Exception e){
    				e.printStackTrace();
    			}
    			intentReceiver = null;
        	}
	}

	@Override
    public void onDestroy() {
    	Log.e(TAG, "WorldClockActivity_onDestroy");

    	super.onDestroy();
    }
	MenuInflater mMenuinflater = null;
    @Override
	public void onResume() {
		// TODO Auto-generated method stub
    	Log.e(TAG, "onResume");
		super.onResume();
		mSelectedOptionItem = false;
		
		prepareOptionsMenu(menu);
	    //[hyunjung78.park][1406] 2011.10.12 START
		if(isLowOnSpace){ 
			isLowOnSpace = false;
			return; 
		}
		//[hyunjung78.park][1406] 2011.10.12 END
		boolean chResult = false;
		chResult = checkDBVer();
		// [suhaeng.lee][1456] 2011.10.19 START
		if(AlarmClockActivity.mSelectedID != 0){
			
			boolean mCheckedSelectedID = CityDBManager.checkDeleteList(this.getActivity(), AlarmClockActivity.mSelectedID);
			if(!mCheckedSelectedID){
				this.getActivity().removeDialog(DELETE_DIALOG);
				this.getActivity().removeDialog(DST_SELECT_DIALOG); //[suhaeng.lee][1456] 2011.10.21
				AlarmClockActivity.mSelectedID = 0;
			}
		}
		
		if(AlarmClockActivity.mDeleteAll){
			boolean mCheckDeleteAll = CityDBManager.checkDeleteAllList(this.getActivity());
			if(!mCheckDeleteAll){
				this.getActivity().removeDialog(DELETEALL_DIALOG);
				this.getActivity().removeDialog(DST_SELECT_DIALOG); //[hyunjung78.park] 2011. 10. 24 https://medic.lge.com/issues/1456
				AlarmClockActivity.mDeleteAll = false;
			}
		}
		// [suhaeng.lee][1456] 2011.10.19 END
		
		if(!chResult){
			 android.util.Log.d(TAG,"WorldClock.java || onResume : [GO! refreshList]");
			 updateDST();  
		}else{
			 android.util.Log.d(TAG,"WorldClock.java || onResume : [NO! refreshList]");
		}
		if(intentReceiver == null)
			initReceiver();
	}

	public void onClick(View v) {
        addCity();
    }
    
    @Override 
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        super.onCreateOptionsMenu(menu,inflater);
		menu.clear();
        inflater.inflate(R.menu.main_menu_worldclock, menu);
        if(mMenuinflater==null)
        	mMenuinflater = inflater;
        this.menu = menu;
    }

    @Override 
    public void onPrepareOptionsMenu(Menu menu) {
    	super.onPrepareOptionsMenu(menu);
    	prepareOptionsMenu(menu); 
    }

    private void prepareOptionsMenu(Menu menu) {

    	if(menu == null)
    		return ;
    	
    	if (mCityManager != null) {
    		
	    	if(menu.findItem(R.id.menu_add)==null){
	    		mMenuinflater.inflate(R.menu.main_menu_worldclock, menu);
	    	}
	    	
    		if(0 < mCityManager.getWCListSize()) {
    			menu.findItem(R.id.menu_add).setEnabled(!isMaximumCount());
    			menu.findItem(R.id.menu_delete).setVisible(true);
    			menu.findItem(R.id.menu_delete_all).setVisible(true);
    		}
    		else {
    			menu.findItem(R.id.menu_add).setEnabled(true);
    			menu.findItem(R.id.menu_delete).setVisible(false);
    			menu.findItem(R.id.menu_delete_all).setVisible(false);
    		}
    	}
    	else 
		{
			menu.findItem(R.id.menu_add).setEnabled(true);
			menu.findItem(R.id.menu_delete).setVisible(false);
			menu.findItem(R.id.menu_delete_all).setVisible(false);
    	}
    }
    
    @Override 
    public boolean onOptionsItemSelected(MenuItem item) {
        if(mSelectedOptionItem)
        	return true;
        
        super.onOptionsItemSelected(item);

        
        switch(item.getItemId()) {
            case(R.id.menu_add) :
                mSelectedOptionItem = true;
                addCity();
                break;
                
            case(R.id.menu_delete) :
				if (mCityManager != null && mCityManager.getWCListSize() == 1) {
					selectedItem = mWCAdapter.getItem(0);
					AlarmClockActivity.mSelectedID = selectedItem.getID();
					showAlertDialogs(DELETE_DIALOG);
				} else {
					moveToDelete();
				}
                break;
            
            case(R.id.menu_delete_all) :
            	if(mWCAdapter.getCount() > 0) {
            		// [suhaeng.lee][1456] 2011.10.19 START
            		AlarmClockActivity.mDeleteAll = true;
            		// [suhaeng.lee][1456] 2011.10.19 END
            		//showDialog(DELETEALL_DIALOG);
            		showAlertDialogs(DELETEALL_DIALOG); //[suhaeng.lee][3174] 2012.01.13
                } else {
                    Toast.makeText(getActivity(), R.string.msg_non_city_list, Toast.LENGTH_SHORT).show();
                }
                break;
            
            default:
            	 mSelectedOptionItem = false;
                return false;
        }
        getActivity().invalidateOptionsMenu();
        return true;
    }
    
    private void updateDST() {
    	boolean mExsitList = CityDBManager.checkList();
    	if(mExsitList){
    		CityDBManager.refreshAddedCity();
    		refreshList();
    	}
    }

    @Override 
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
        AdapterView.AdapterContextMenuInfo info = null;

        try {
            info = (AdapterView.AdapterContextMenuInfo)menuInfo;
        }
        catch(ClassCastException e) {
            return;
        }
        // [minjoong.park][2094] 2011.11.29 START
        final int index = info.position;
        // [minjoong.park][2094] 2011.11.29 END
        try{
            CityInformation cityInfo = mWCAdapter.getItem(index);
            menu.setHeaderTitle(cityInfo.getCityName());
            menu.add(Menu.NONE, CONTEXT_DST, Menu.NONE, getResources().getString(R.string.dst));
            menu.add(Menu.NONE, CONTEXT_DELETE, Menu.NONE, getResources().getString(R.string.menu_multiselect));
        	
        }catch(Exception e){
        	e.printStackTrace();
        }
    }

    @Override 
    public boolean onContextItemSelected(MenuItem item) {
        AdapterView.AdapterContextMenuInfo menuInfo = null;

        menuInfo = (AdapterView.AdapterContextMenuInfo)item.getMenuInfo();
        // [minjoong.park][2094] 2011.11.29 START
        final int index = menuInfo.position;
        // [minjoong.park][2094] 2011.11.29 END
        switch(item.getItemId())    {
            case CONTEXT_DELETE:
                selectedItem = mWCAdapter.getItem(index);
                // [suhaeng.lee][1456] 2011.10.19 START
                AlarmClockActivity.mSelectedID = selectedItem.getID();
                // [suhaeng.lee][1456] 2011.10.19 END
                //showDialog(DELETE_DIALOG);
                showAlertDialogs(DELETE_DIALOG); //[suhaeng.lee][3174] 2012.01.13
                return true;
            case CONTEXT_DST:
                selectedItem = mWCAdapter.getItem(index);
                // [suhaeng.lee][1456] 2011.10.21 START
                AlarmClockActivity.mSelectedID = selectedItem.getID();
                // [suhaeng.lee][1456] 2011.10.21 END
                selectIndexDST = selectedItem.getUpdateMode();
                Log.e(TAG, "selectIndexDST => " + selectIndexDST);
                //showDialog(DST_SELECT_DIALOG);
                showAlertDialogs(DST_SELECT_DIALOG); //[suhaeng.lee][3174] 2012.01.13
                return true;
                default :
        }

        return super.onContextItemSelected(item);
    }
  
    @Override 
    public void onActivityResult(int requestCode, int resultCode, Intent intent) {
    	super.onActivityResult(requestCode, resultCode, intent);
    	
    	switch(requestCode){
	    	case SEARCHLIST_ACTIVITY:
	    	case SEARCHMAP_ACTIVITY:
	    		cityListView.setTranscriptMode(ListView.TRANSCRIPT_MODE_ALWAYS_SCROLL );
	        	refreshList();
	        	prepareOptionsMenu(this.menu);
	        	int id = CityDBManager.getAddCityId();
	        	if(id != -1)
	        	{
	        		CityInformation item = mCityManager.getTimeZoneCityInfo(id);
	        		//[start][yeonju7.kim][IT][WBT_11][P940][45900] 2011.09.08 
	        		if(item.getCountryName()!=null) {
	        			CityDBManager.initAddCityId();
	        		}
	        		//[end][yeonju7.kim][IT][WBT_11][P940][45900] 2011.09.08 
	        	}
	        	break;
	    	case MULTIDELETE_ACTIVITY:
	        	refreshList();
	        	prepareOptionsMenu(this.menu);
	        	break;
	        default:
	        	break;
    	}
    }
    
    private View initView(LayoutInflater inflater, ViewGroup container) {
    	View view = inflater.inflate(R.layout.worldclock_city_list, container, false);
    	
        cityListView    = (ListView)view.findViewById(R.id.list_Citys);
        noCityView = (View)view.findViewById(R.id.noCityTop);


		cityListView.setOnCreateContextMenuListener(this);
		set_Visibility(cityInfoArray);
		mWCAdapter = new WorldClockAdapter(getActivity(), R.layout.worldclock_city_list_item, cityInfoArray);

        cityListView.setAdapter(mWCAdapter);
        
        refreshTime();
        
        
        
        return view;
    }

    private void set_Visibility(ArrayList<CityInformation> cityInfoArray) {
    	if(cityInfoArray.size() == 0) {
    		noCityView.setVisibility(View.VISIBLE);
    		cityListView.setVisibility(View.GONE);
    	}
    	else {
    		cityListView.setVisibility(View.VISIBLE);
    		noCityView.setVisibility(View.GONE);
    	}
    }
    
    private void initReceiver() {
        intentReceiver = new TheBroadcastReceiver();
        IntentFilter filter = new IntentFilter(); 
        filter.addAction(Intent.ACTION_TIME_TICK);
        filter.addAction(Intent.ACTION_TIMEZONE_CHANGED);
        filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
        getActivity().registerReceiver(intentReceiver, filter);   
    }

    private void refreshList() {
    	if(cityInfoArray == null)
    		cityInfoArray = new ArrayList<CityInformation>();
    	else 
    		cityInfoArray.clear();
    	if(mCityManager==null){
    		return;
    	}
        cityInfoArray.addAll(mCityManager.getWorldClockList(getActivity().getApplicationContext()));
        set_Visibility(cityInfoArray);
        refreshTime();
    }
    
    private void refreshTime() {
        long systemOffset = getSystemOffset();
        mWCAdapter.setSystemOffset(systemOffset);
        getActivity().runOnUiThread(new Runnable() {
			public void run() {
				mWCAdapter.notifyDataSetChanged();
			}
		});
    }

    private long getSystemOffset() {
        Time today = new Time();
        today.setToNow();
        return (long)(today.gmtoff* 1000);
    }

    public void deleteCityList() {
        mCityManager.deleteCity(selectedItem);
        Toast.makeText(getActivity(), getString(R.string.delete_toast), Toast.LENGTH_SHORT).show();
        refreshList();
        prepareOptionsMenu(this.menu);
    }
    
    private void deleteAllCityList() {
        mCityManager.deleteAllCity();
        Toast.makeText(getActivity(), getString(R.string.delete_toast), Toast.LENGTH_SHORT).show();
       // refreshList();
		//cityInfoArray.clear();
		if(cityInfoArray != null){
			refreshList();
		    set_Visibility(cityInfoArray);		    
	        prepareOptionsMenu(this.menu);
		}
    }
    
    private void addCity() {
        Intent  intent;
        WCPreferences wcPref = new WCPreferences(getActivity());
        
        if(isMaximumCount()) {
	    	Toast.makeText(getActivity().getApplicationContext(), R.string.worldclock__city_exceed, Toast.LENGTH_SHORT).show();
	    	return;
	    }
        
        if(wcPref.getSearchType()) {
        	intent = new Intent(getActivity(), ListSearchActivity.class);
            startActivityForResult(intent, SEARCHLIST_ACTIVITY);
        }
        else {
        	intent = new Intent(getActivity(), MapSearchActivity.class); 
            startActivityForResult(intent, SEARCHMAP_ACTIVITY);
        }
    }
    
    private boolean isMaximumCount() {
	    if(mCityManager.getWCListSize() >= MAXIMUM_WORLDCLOCK_LIST_SIZE) return true;
        return false;
    }
    
    private void moveToDelete() {
    	Intent intent = new Intent(getActivity(), DeleteListActivity.class);
    	startActivityForResult(intent, MULTIDELETE_ACTIVITY);
    }
    
    private void modifyDST(int selected) {
        mCityManager.daylight(selectedItem.getID(), selected);
        refreshList();
    }

    /**
     * @author lge.com
     */
    public class TheBroadcastReceiver extends BroadcastReceiver { 
		public void onReceive(Context context, Intent intent) {
			
    		if(cityListView.getTranscriptMode()== ListView.TRANSCRIPT_MODE_ALWAYS_SCROLL )
    			cityListView.setTranscriptMode(ListView.TRANSCRIPT_MODE_DISABLED);

			if (intent.getAction().equals(Intent.ACTION_TIME_TICK)) {
				
				Calendar cal = Calendar.getInstance();
				DateFormat df = new SimpleDateFormat("mm");
				
				Date mCurrentTime = cal.getTime();
				
				String mCuurentCompareTime = df.format(mCurrentTime);
				
				Log.d(TAG,"Time Tick occured the event!!!!");
				if(mCuurentCompareTime.equals("30") || 
						mCuurentCompareTime.equals("45") || 
						mCuurentCompareTime.equals("00")){
					Log.e(TAG, "Update!!!!!!!!!!! => " + mCuurentCompareTime);
					updateDST();
				}else{
					refreshTime();
				}
			}else if(intent.getAction().equals(Intent.ACTION_TIMEZONE_CHANGED)) {
				Log.d(TAG,"TIMEZONE_CHANGED occured the event!!!!");
				refreshList();
            }else if((intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION) || intent.getAction().equals(WifiManager.WIFI_STATE_CHANGED_ACTION))
            				&& receiverNetworkFlag) {
            	Log.i(TAG, "intent.getAction() : " + intent.getAction());
        		ConnectivityManager mconnectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        		NetworkInfo activeNetInfo = mconnectivityManager.getActiveNetworkInfo();
                if(activeNetInfo != null && activeNetInfo.isConnected()) {
                	// DST update success.
                	new UpdateDaylightInfoList().execute();
                	refreshList();
                	Toast.makeText(getActivity(), R.string.dst_update_success_str, Toast.LENGTH_SHORT).show();
                	receiverNetworkFlag = false;
                }
            }
		}
    }
    
    private class UpdateDaylightInfoList extends AsyncTask<String, Integer, Boolean>
    {
    	private SUIProgressDialog mProgressDialog;
        private ArrayList<CityInformation> worldClockList =
                                        new ArrayList<CityInformation>();
		private boolean isInterrupt = false;

		 @Override 
		 protected void onPreExecute() {
			 worldClockList = mCityManager.getWorldClockList(getActivity());

			 mProgressDialog = new SUIProgressDialog(getActivity());

			 if(mProgressDialog != null) {
				 mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
				 mProgressDialog.setMax(mCityManager.getWCListSize());
				 mProgressDialog.setProgress(0);
				 mProgressDialog.setButton(DialogInterface.BUTTON_NEUTRAL, 
						 getResources().getString(R.string.alert_dialog_cancel), 
						 new DialogInterface.OnClickListener() {
					 public void onClick(DialogInterface dialog, int which) {
						 cancel(true);
					 }
				 });

				 mProgressDialog.setOnDismissListener(new OnDismissListener() {
					 
					 public void onDismiss(DialogInterface dialog) {
						 cancel(true);
					 }
				 });

				 mProgressDialog.show();
				 super.onPreExecute();
			 }
		 } 

		 private boolean isDSTdata = true;
		 private String notdataCityName = "";

        @Override
        protected Boolean doInBackground(final String... arg0) {
            int current_index = 1;
            int osbDaylight = -1;
            boolean retValue = true;
            notDSTUpdateCount = 0;
            
            for(CityInformation item : worldClockList) {
            	if(isInterrupt ) break;

                osbDaylight = WeatherUtil.getDaylight(item.getRequest());
                if(osbDaylight >= 0) {
                    boolean flag = mCityManager.daylight(item.getID(), osbDaylight);
                    if(!flag) retValue = false;
                    if(osbDaylight == 0) notDSTUpdateCount++;
                }
                else if(-2 == osbDaylight)
                {
                	isDSTdata = false;
                	notdataCityName = item.getCityName();
                }
                else {
                	return retValue = false;
                }
                publishProgress(current_index, item.getID());
                current_index++; 
            }
            return retValue;
        } 

        @Override 
        protected void onProgressUpdate(final Integer... progress) { 
        	String[] widgetExtra = new String[3];
            mProgressDialog.setProgress(progress[0]); 
            //send the broadcast to widget
            Intent toWidget = new Intent("dstaccuweatherupdate");
            widgetExtra = mCityManager.getCityNameAndTimezone(getActivity(), progress[1]);
            toWidget.putExtra("extravalue", widgetExtra);
            getActivity().sendBroadcast(toWidget);
        } 

        @Override
        protected void onPostExecute(final Boolean result) {
        	if(mProgressDialog.isShowing())
        		mProgressDialog.dismiss();
            if(true == result){
            	Toast.makeText(getActivity(), R.string.dst_update_success_str, Toast.LENGTH_SHORT).show();
            }
            refreshList();
        } 

        @Override 
        protected void onCancelled() 
        { 
        	isInterrupt = true;
            super.onCancelled(); 
        }
    }
    
    
	 
	 /** When updating database, progress pop up is given. */
	 private class UpdateDataBase extends AsyncTask<Integer, Integer, Boolean>
	 {
		 private SUIProgressDialog mProgressDialog;

		 @Override 
		 protected void onPreExecute() {
			 mProgressDialog = new SUIProgressDialog(getActivity());
			 String progressMsg = getResources().getString(R.string.sp_db_update_NORMAL) + "(%s)";
			 //WBT td 198070 fix
			 if (mProgressDialog != null)
			 {
				 mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);		
				 mProgressDialog.setTextAppearance(R.style.worldclock_dbupdate_text);
				 mProgressDialog.setProgressMessageFormat(progressMsg);
				 mProgressDialog.setMax(100);
				 mProgressDialog.setProgress(0);
				 mProgressDialog.setCancelable(false);

            	mProgressDialog.show();
            }
            super.onPreExecute(); 
            
        } 

		 @Override
		 protected Boolean doInBackground(final Integer... arg0) {
			 Context context = getActivity();

			 byte[] buffer = new byte[1024];
			 int currentRead = 0;
			 int current_index = 0;
			 
			 FileOutputStream fos = null;
			 InputStream is = null;
			 
			 try {
				 is = CityDBManager.getWorldClockDBInputStream(context);
				 fos = CityDBManager.getWorldClockDBFileOutputStream(context);
	
				 // WBT TD#200942/200943/200944/200945 fixed
				 if (is == null || fos == null) {
					 return false;
				 }
			 
				 while((currentRead = is.read(buffer)) > 0){
					 fos.write(buffer, 0, currentRead);
					 current_index++; 
					 publishProgress(current_index);
				 }
			 }
			 catch (Exception e) {
				 CityDBManager.deleteWorldClockDBFile(context);
				 return false;
			 }
			 // WBT TD#220937 fixed
			 finally {
				 CityDBManager.closeWorldClockDatabaseFile(context, is, fos);
			 }

			 return true;
		 } 

		 @Override 
		 protected void onProgressUpdate(final Integer... progress) { 
			 mProgressDialog.setProgress(progress[0]); 
		 } 

		 @Override
		 protected void onPostExecute(final Boolean result) {
			 // db version pref update
			 try {
				 mCityManager = CityDBManager.getInstance(getActivity());
			 } catch (IOException e) {	
				 e.printStackTrace();
			 }
			 cityInfoArray.addAll(mCityManager.getWorldClockList(getActivity()));
			 mProgressDialog.dismiss();
			 refreshList();
		 } 
		 
		 
	 }
	 
//	 void showDialog(int id){
//		 DialogFragment newFragment = new MyAlertDialogFragment(id);
//		 newFragment.show(getFragmentManager(), "dialog");
//		 
//	 }
	 //[suhaeng.lee][3174] 2012.01.13 START
	 void showAlertDialogs(int id){
		Log.e(TAG, "selectIndexDST => " + selectIndexDST);
		
        switch(id) {
	        case (DELETE_DIALOG) : {
	            AlertDialog.Builder dialog = new AlertDialog.Builder(getActivity());
	            dialog.setTitle(R.string.menu_multiselect)
	            .setMessage(R.string.sp_THISCITY_NORMAL)
//	            .setIcon(android.R.drawable.ic_dialog_alert)
	            .setIconAttribute(android.R.attr.alertDialogIcon)
	            .setPositiveButton(R.string.timer_set_alerttone_ok, new DialogInterface.OnClickListener() {
	                public void onClick(DialogInterface dialog, int which) {
	                    deleteCityList();
	                }
	            })
	            .setNegativeButton(R.string.alert_dialog_cancel, null)
	            .show();
	            break;
	        }
	        case (DELETEALL_DIALOG) : {
	            AlertDialog.Builder dialog = new AlertDialog.Builder(getActivity());
	            dialog.setTitle(R.string.menu_deleteall)
//	            .setIcon(android.R.drawable.ic_dialog_alert)
	            .setIconAttribute(android.R.attr.alertDialogIcon)
	            .setMessage(R.string.all_delete_message)
	            .setPositiveButton(R.string.timer_set_alerttone_ok, new DialogInterface.OnClickListener() {
	                public void onClick(DialogInterface dialog, int which) {
	                    deleteAllCityList();
	                }
	            })
	            .setNegativeButton(R.string.alert_dialog_cancel, null)
	            .show();
	            break;
	        }
	        
	        case (DST_SELECT_DIALOG) : {
	        	Log.e(TAG, "selectIndexDST => " + selectIndexDST);
	        	AlertDialog.Builder dialog = new AlertDialog.Builder(getActivity());
	          
	        	dialog.setTitle(R.string.dst)
	        	.setSingleChoiceItems(R.array.sp_DST_Time_NORMAL, selectIndexDST, new DialogInterface.OnClickListener() {
	        		public void onClick(DialogInterface dialog, int whichButton) {
	        			/* User clicked on a radio button do some stuff */
	        			selectIndexDST = whichButton;
	        			Log.e(TAG, "selectIndexDST => " + selectIndexDST);
	        			
	        			/* User clicked Yes so do some stuff */
	        			String[] widgetExtra = new String[3];
	        			modifyDST(selectIndexDST);
	        			dialog.dismiss();
	        			//send the broadcast to widget
	        			Intent toWidget = new Intent("dstmanualupdate");	// manual
	        			widgetExtra = mCityManager.getCityNameAndTimezone(getActivity(), selectedItem.getID());
	        			Log.i(TAG, "WidgetExtra : " + widgetExtra[0] + ", " + widgetExtra[1] + ", " + widgetExtra[2]);
	        			toWidget.putExtra("extravalue", widgetExtra);
	        			getActivity().sendBroadcast(toWidget);
	        		}
	        	})
	        	.setNegativeButton(R.string.alert_dialog_cancel, new DialogInterface.OnClickListener() {
	        		public void onClick(DialogInterface dialog, int whichButton) {
	        			dialog.dismiss();
	        		}
	        	})
	        	.show();
	        	break;
	        }
        }
		 
	}
	//[suhaeng.lee][3174] 2012.01.13 END

//	 class MyAlertDialogFragment extends DialogFragment{
//		 
//		 public MyAlertDialogFragment(int id){
//			 Bundle args = new Bundle();
//			 args.putInt("id", id);
//			 setArguments(args);
//		 }
//		 
//		@Override 
//	    public Dialog onCreateDialog(Bundle savedInstanBundle){
//	        int id = getArguments().getInt("id");		 	
//	        switch(id) {
//	            case (DELETE_DIALOG) : {
//	                AlertDialog.Builder dialog = new AlertDialog.Builder(getActivity());
//	                return dialog.setTitle(R.string.menu_multiselect)
//	                .setMessage(R.string.sp_THISCITY_NORMAL)
//	                .setIcon(android.R.drawable.ic_dialog_alert)
//	                .setPositiveButton(R.string.timer_set_alerttone_ok, new DialogInterface.OnClickListener() {
//	                    public void onClick(DialogInterface dialog, int which) {
//	                        deleteCityList();
//	                    }
//	                })
//	                .setNegativeButton(R.string.alert_dialog_cancel, null)
//	                .create();
//	            }
//	            case (DELETEALL_DIALOG) : {
//	                AlertDialog.Builder dialog = new AlertDialog.Builder(getActivity());
//	                return dialog.setTitle(R.string.menu_deleteall)
//	                .setIcon(android.R.drawable.ic_dialog_alert)
//	                .setMessage(R.string.all_delete_message)
//	                .setPositiveButton(R.string.timer_set_alerttone_ok, new DialogInterface.OnClickListener() {
//	                    public void onClick(DialogInterface dialog, int which) {
//	                        deleteAllCityList();
//	                    }
//	                })
//	                .setNegativeButton(R.string.alert_dialog_cancel, null)
//	                .create();
//	            }
//	            
//	            case (DST_SELECT_DIALOG) : {
//	            	Log.e(TAG, "selectIndexDST => " + selectIndexDST);
//	            	AlertDialog.Builder dialog = new AlertDialog.Builder(getActivity());
//	              
//	            	return dialog.setTitle(R.string.dst)
//	            	.setSingleChoiceItems(R.array.sp_DST_Time_NORMAL, selectIndexDST, new DialogInterface.OnClickListener() {
//	            		public void onClick(DialogInterface dialog, int whichButton) {
//	            			/* User clicked on a radio button do some stuff */
//	            			selectIndexDST = whichButton;
//	            			Log.e(TAG, "selectIndexDST => " + selectIndexDST);
//	            			
//	            			/* User clicked Yes so do some stuff */
//	            			String[] widgetExtra = new String[3];
//	            			modifyDST(selectIndexDST);
//	            			MyAlertDialogFragment.this.dismiss();
//	            			//send the broadcast to widget
//	            			Intent toWidget = new Intent("dstmanualupdate");	// manual
//	            			widgetExtra = mCityManager.getCityNameAndTimezone(getActivity(), selectedItem.getID());
//	            			Log.i(TAG, "WidgetExtra : " + widgetExtra[0] + ", " + widgetExtra[1] + ", " + widgetExtra[2]);
//	            			toWidget.putExtra("extravalue", widgetExtra);
//	            			getActivity().sendBroadcast(toWidget);
//	            		}
//	            	})
//	            	// TD 60037 fixed
////		            	.setPositiveButton(R.string.timer_set_alerttone_ok, new DialogInterface.OnClickListener() {
////		            		public void onClick(DialogInterface dialog, int whichButton) {
////		            			/* User clicked Yes so do some stuff */
////		            			String[] WidgetExtra = new String[3];
////		            			ModifyDST(selectIndexDST);
////		            			removeDialog(DST_SELECT_DIALOG);
////		                      
////		            			//send the broadcast to widget
////		            			Intent toWidget = new Intent("dstmanualupdate");	// manual
////		            			WidgetExtra = mCityManager.getCityNameAndTimezone(WorldClockActivity.this, selectedItem.getID());
////		            			Log.i(TAG, "WidgetExtra : " + WidgetExtra[0] + ", " + WidgetExtra[1] + ", " + WidgetExtra[2]);
////		            			toWidget.putExtra("extravalue", WidgetExtra);
////		            			sendBroadcast(toWidget);
////		            		}
////		            	})
//	            	.setNegativeButton(R.string.alert_dialog_cancel, new DialogInterface.OnClickListener() {
//	            		public void onClick(DialogInterface dialog, int whichButton) {
//	            			MyAlertDialogFragment.this.dismiss();
//	            		}
//	            	})
//	            	.create();
//	            }
//	        }
//	        return null;
//	    }
//	 }
}
